package ferp.android.views;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import ferp.android.managers.DeckManager;
import ferp.core.card.Card;

/**
 * User: user
 * Date: 6/24/11 11:26 AM
 */
public class CardView extends ImageView implements View.OnTouchListener,
    DeckManager.RefreshableView
{
  public static interface Listener
  {
    void onMovingStarted(CardView cv, Point touch);
    void onMoving(CardView cv, int x, int y);
    void onMovingEnded(CardView cv);
  }

  // 100x140 card
  public static int WIDTH = 90;
  public static int HEIGHT = 140;

  public CardView(Context context, Listener listener)
  {
    super(context);

    this.listener = listener;

    setOnTouchListener(this);
    setVisibility(GONE);

    DeckManager.instance(context).register(this);
  }

  // set the card to view
  public void set(Card card, boolean show)
  {
    this.card = card;
    this.shown = show;

    // show the card
    show(shown);
  }

  public void show(boolean flag)
  {
    DeckManager dm = DeckManager.instance(getContext());

    shown = flag;

    // set the appropriate drawable
    setBackgroundDrawable(shown ? dm.getCardFront(card) : dm.getCardBack());

    // actually show it
    if (getVisibility() != VISIBLE)
      setVisibility(VISIBLE);

/*
    if (shown)
    {
      Drawable d = faces.get(card);

      if (d == null)
      {
        setBackgroundResource(resource);
        faces.put(card, getBackground());
      }
      else
        setBackgroundDrawable(d);
    }
    else
    {
      if (back == null)
      {
        setBackgroundResource(R.drawable.card_back);
        back = getBackground();
      }
      else
        setBackgroundDrawable(back);
    }
*/
}

  public boolean isFaceUp() {return shown;}

  public void layout(int x, int y)
  {
    // call super.layout, as we know the exact values of width and height
    layout(x, y, x + WIDTH, y + HEIGHT);
  }

  // get attached card
  public Card card() {return card;}

  public boolean onTouch(View view, MotionEvent event)
  {
    if (listener != null)
      switch (event.getAction())
      {
        case MotionEvent.ACTION_DOWN:
          listener.onMovingStarted(this, new Point((int)event.getRawX(), (int)event.getRawY()));
          break;

        case MotionEvent.ACTION_MOVE:
          listener.onMoving(this, (int)event.getRawX(), (int)event.getRawY());
          break;

        case MotionEvent.ACTION_UP:
          listener.onMovingEnded(this);
          break;
      }

    return true;
  }

  @Override
  public void refresh()
  {
    if (card != null)
      show(shown);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
  {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    setMeasuredDimension(WIDTH, HEIGHT);
  }

/*
  @Override
  protected void onDraw(Canvas c)
  {
    super.onDraw(c);

    Bitmap scaled = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.back01), CardView.WIDTH, CardView.HEIGHT, false);
    final Paint anti = new Paint(Paint.ANTI_ALIAS_FLAG);

    c.drawARGB(0, 0, 0, 0);
    anti.setColor(0xff424242);
    c.drawRoundRect(rectangleF, CORNER_RADIUS, CORNER_RADIUS, anti);
    anti.setXfermode(porterDuffXfermode);
    c.drawBitmap(scaled, rectangle, rectangle, anti);

    c.drawRoundRect(rectangleF, CORNER_RADIUS, CORNER_RADIUS, black);

    // recycle resources
    scaled.recycle();
  }
*/

  private BitmapDrawable prepareBitmap(int resource)
  {
    /*
    Bitmap scaled = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), resource), CardView.WIDTH - 2, CardView.HEIGHT - 2, false);
    Bitmap result = Bitmap.createBitmap(CardView.WIDTH, CardView.HEIGHT, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(result);
    //final Paint anti = new Paint(Paint.ANTI_ALIAS_FLAG);

    // round corners
    c.drawARGB(0, 0, 0, 0);
    anti.setXfermode(null);
    c.drawRoundRect(border, CORNER_RADIUS, CORNER_RADIUS, anti);
    anti.setXfermode(porterDuffXfermode);
    c.drawBitmap(scaled, 1, 1, anti);
    // draw black border
    c.drawRoundRect(border, CORNER_RADIUS, CORNER_RADIUS, black);

    // recycle resources
    scaled.recycle();

    return new BitmapDrawable(result);
    */

    return new BitmapDrawable(BitmapFactory.decodeResource(getResources(), resource));
  }

/*
  private void cache(int index, String name)
  {
    // user supplied card images?
    faces[index] = usci ? getUserDefinedCardImage(name) : getPredefinedCardImage(name, null);
  }

  private Drawable getPredefinedCardImage(String name, String error)
  {
    Resources resources = getResources();
    // card image resource
    int image = resources.getIdentifier(name, "drawable", getContext().getPackageName());

    if (error != null)
      Log.debug(Log.TAG, "loading predefined card image - reason: " + error);

    return new BitmapDrawable(BitmapFactory.decodeResource(resources, image));
  }

  private Drawable getUserDefinedCardImage(String name)
  {
    try
    {
      // do we already have the zip file object?
      if (zf == null)
      {
        File esd = Environment.getExternalStorageDirectory();

        if (esd == null || !esd.exists())
          return getPredefinedCardImage(name, "no external storage directory");

        File zip = new File(esd, "cards.zip");

        if (!zip.exists())
          return getPredefinedCardImage(name, "no zip file");

        zf = new ZipFile(zip);
      }

      ZipEntry e = zf.getEntry(name + ".png");

      if (e == null)
        getPredefinedCardImage(name, "card image " + name + " not found");

      Log.debug(Log.TAG, "loading external card image " + name);

      return new BitmapDrawable(BitmapFactory.decodeStream(zf.getInputStream(e)));
    }
    catch (IOException e)
    {
      return getPredefinedCardImage(name, e.getMessage());
    }
  }
*/

  // currently shown card
  private Card card;
  // flipped
  private boolean shown = false;

  // listener for different card view's events
  private Listener listener;
}
